package com.quasar.hpatient.view.prescription;

import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.quasar.hpatient.R;
import com.quasar.hpatient.base.BaseActivity;
import com.quasar.hpatient.constant.ConstantManger;
import com.quasar.hpatient.model.custommodel.LifecycleRecordsBean;
import com.quasar.hpatient.model.custommodel.LifecycleTest;
import com.quasar.hpatient.model.medicalmodel.HealthRecordsBean;
import com.quasar.hpatient.model.medicalmodel.LifecycleHead;
import com.quasar.hpatient.model.medicalmodel.LifecycleYear;
import com.quasar.hpatient.onInterface.AnotherResultListener;
import com.quasar.hpatient.presenter.HealthRecordsPresenter;
import com.quasar.hpatient.utils.DialogHelp;
import com.quasar.hpatient.view.adapter.LifecycleAdapter;
import com.quasar.hpatient.widget.dialog_my_date_code;
import com.vise.log.ViseLog;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * 健康史
 */
@EActivity(R.layout.activity_history_life)
public class HistoryLifeActivity extends BaseActivity implements AnotherResultListener<HealthRecordsBean>, dialog_my_date_code.OnCustomDialogDetermineListener, BaseQuickAdapter.RequestLoadMoreListener, SwipeRefreshLayout.OnRefreshListener {

    private HealthRecordsPresenter healthRecordsPresenter;
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    public static final int ACTION_TYPE_LAST = 6;
    //记录时间
    String DateTime="0";
    private LifecycleAdapter lifecycleAdapter;
    int page = 1;
    //条件查询
    String LifecycleType = "0";
    private int delayMillis = 1000;//设置刷新等待的时间
    //判断下一页是否存在数据
    private boolean onLoadMore = false;


    @ViewById(R.id.rv_list)
    RecyclerView mRecyclerView;
    //类型选择
    @ViewById(R.id.imageView4)
    TextView imageView4;
    //时间选择
    @ViewById(R.id.tv_time)
    TextView tv_time;
    @ViewById(R.id.por_tv_title)
    TextView por_tv_title;
    @ViewById(R.id.tv_titles)
    TextView tv_titles;
    @ViewById(R.id.swipeLayout)
    SwipeRefreshLayout swipeLayout;

    @AfterViews
    void init() {
        initView();
        initData();
        mRecyclerView.setAdapter(lifecycleAdapter);
    }

    @Override
    protected void initView() {
        initToolbar();
        swipeLayout.setOnRefreshListener(this);
        swipeLayout.setColorSchemeColors(Color.rgb(47, 223, 189));
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        por_tv_title.setText("按时间查询");
        imageView4.setText("全部");
        tv_titles.setText("按类型查询");
        tv_time.setText("全部");


        lifecycleAdapter = new LifecycleAdapter(this, null);
        lifecycleAdapter.setOnLoadMoreListener(this, mRecyclerView);
        GridLayoutManager manager = new GridLayoutManager(this, 1);
        mRecyclerView.setLayoutManager(manager);
    }

    @Override
    protected void initData() {
        healthRecordsPresenter = new HealthRecordsPresenter(this);
        healthRecordsPresenter.LXT_HealthRecords("0", endTime, page + "", LifecycleType);
    }


    //根据类型查询
    @Click(R.id.rl_title)
    public void rl_title() {

        DialogHelp.getSelectDialog(this, "根据类型查询", getResources().getStringArray(R.array.choose_type), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                goToTypequery(i);
            }
        }).show();

    }

    //按时间段查询
    @Click(R.id.ll_rl_title)
    public void ll_rl_title() {
        DialogHelp.getSelectDialog(this, "时间段查询", getResources().getStringArray(R.array.choose_history_life), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                goToSelectPicture(i);
            }
        }).show();
    }

    public void goToTypequery(int index) {
        page=1;
        String[] Strnum = getResources().getStringArray(R.array.choose_type);
        tv_time.setText(Strnum[index]);
        switch (index) {

            case 0:
                LifecycleType = 0 + "";
                healthRecordsPresenter.LXT_HealthRecords(DateTime, endTime, page + "", LifecycleType);
                break;
            case 1:
                LifecycleType = 1 + "";
                healthRecordsPresenter.LXT_HealthRecords(DateTime, endTime, page + "", LifecycleType);
                break;
            case 2:
                LifecycleType = 2 + "";
                healthRecordsPresenter.LXT_HealthRecords(DateTime, endTime, page + "", LifecycleType);
                break;
            case 3:
                LifecycleType = 3 + "";
                healthRecordsPresenter.LXT_HealthRecords(DateTime, endTime, page + "", LifecycleType);
                break;
            case 4:
                LifecycleType = 4 + "";
                healthRecordsPresenter.LXT_HealthRecords(DateTime, endTime, page + "", LifecycleType);
                break;
        }
    }


    List<HealthRecordsBean> healthRecordsBeanList = new ArrayList<>();

    @Override
    public void onSuccess(HealthRecordsBean ta) {
        HealthRecordsBean t = new HealthRecordsBean();
//        //判断page是否是下拉还是上拉
        if (page == 1) {
            healthRecordsBeanList.clear();
            healthRecordsBeanList.add(ta);
            onLoadMore = false;
        } else {
            healthRecordsBeanList.add(ta);
            if(ta.getTroubleDetailList().size()>0 || ta.getPatientCaseHistoryList().size()>0
                    || ta.getDiagnoseDetailsList().size()>0 || ta.getInspectionEventsList().size()>0||
                    ta.getPharmacyRecordsList().size()>0){
            }else{
                onLoadMore = true;
            }
        }

        for (int a = 0; a < healthRecordsBeanList.size(); a++) {
            t.setDiagnoseDetailsList(healthRecordsBeanList.get(a).getDiagnoseDetailsList());
            t.setInspectionEventsList(healthRecordsBeanList.get(a).getInspectionEventsList());
            t.setPatientCaseHistoryList(healthRecordsBeanList.get(a).getPatientCaseHistoryList());
            t.setTroubleDetailList(healthRecordsBeanList.get(a).getTroubleDetailList());
            t.setPharmacyRecordsList(healthRecordsBeanList.get(a).getPharmacyRecordsList());
        }

//
        List<LifecycleYear> lifecycleTestList = new ArrayList<>();
        List<LifecycleHead> lifecycleHeads = new ArrayList<>();
        List<LifecycleYear.LifecycleTesmouth> mlifecycleTesmouths = new ArrayList<>();

        if (t != null) {
            //存放数据
            Map<String, String> map = new HashMap<>();
            //判断诊断信息
            if (t.getDiagnoseDetailsList() != null) {
                for (int i = 0; i < t.getDiagnoseDetailsList().size(); i++) {
                    map.put(t.getDiagnoseDetailsList().get(i).getCheckDateTime().substring(0, 10)
                            , "");
                }
            }
//            //判断事件
            if (t.getInspectionEventsList() != null) {
                for (int i = 0; i < t.getInspectionEventsList().size(); i++) {
                    map.put(t.getInspectionEventsList().get(i).getEventTime().substring(0, 10)
                            , "");  //时间
                }
            }
            //判断调药记录
            if (t.getPharmacyRecordsList() != null) {
                for (int i = 0; i < t.getPharmacyRecordsList().size(); i++) {
                    map.put(t.getPharmacyRecordsList().get(i).getEditTime().substring(0, 10)
                            , "");  //时间
                }
            }
            //判断病历
            if (t.getPatientCaseHistoryList() != null) {
                for (int i = 0; i < t.getPatientCaseHistoryList().size(); i++) {
                    map.put(t.getPatientCaseHistoryList().get(i).getMrdateTime().substring(0, 10)
                            , "");
                }
            }
            //添加患者事件
            if (t.getTroubleDetailList() != null) {
                for (int i = 0; i < t.getTroubleDetailList().size(); i++) {
                    map.put(t.getTroubleDetailList().get(i).getLogTime().substring(0, 10)
                            , "");
                }
            }
            //时间相同的提取出来
            Map<String, LifecycleRecordsBean> map1 = new TreeMap<>(new Comparator<String>() {
                public int compare(String obj1, String obj2) {
                    // 降序排序
                    return obj2.compareTo(obj1);
                }
            });
            Map<String, String> maptime = new TreeMap<>(new Comparator<String>() {
                public int compare(String obj1, String obj2) {
                    // 降序排序
                    return obj2.compareTo(obj1);
                }
            });

            Map<String, String> mapmouth = new TreeMap<>(new Comparator<String>() {
                public int compare(String obj1, String obj2) {
                    // 降序排序
                    return obj2.compareTo(obj1);
                }
            });
            Map<String, String> mapyear = new TreeMap<>(new Comparator<String>() {
                public int compare(String obj1, String obj2) {
                    // 降序排序
                    return obj2.compareTo(obj1);
                }
            });

            for (String time : map.keySet()) {
                LifecycleRecordsBean lifecycleRecordsBean = new LifecycleRecordsBean();
                List<LifecycleRecordsBean.DiagnoseDetailsListBean> diagnoseDetailsListBeen = new ArrayList<>();
                List<LifecycleRecordsBean.PharmacyRecordsListBean> pharmacyRecordsListBeen = new ArrayList<>();
                List<LifecycleRecordsBean.InspectionEventsListBean> inspectionEventsListBeen = new ArrayList<>();
                List<LifecycleRecordsBean.PatientCaseHistoryList> patientCaseHistoryLists = new ArrayList<>();
                List<LifecycleRecordsBean.TroubleDetailListBean> troubleDetailLists = new ArrayList<>();

                //诊断信息
                for (int i = 0; i < t.getDiagnoseDetailsList().size(); i++) {

                    if (time.equals(t.getDiagnoseDetailsList().get(i).getCheckDateTime().substring(0, 10))) {
                        LifecycleRecordsBean.DiagnoseDetailsListBean diagnoseDetailsListBean = new LifecycleRecordsBean.DiagnoseDetailsListBean();
                        diagnoseDetailsListBean.setDiagnoseTime(t.getDiagnoseDetailsList().get(i).getDiagnoseTime());
                        diagnoseDetailsListBean.setCheckDateTime(t.getDiagnoseDetailsList().get(i).getCheckDateTime());
                        diagnoseDetailsListBean.setDoctorId(t.getDiagnoseDetailsList().get(i).getDoctorId());
                        diagnoseDetailsListBean.setContent(t.getDiagnoseDetailsList().get(i).getContent());
                        diagnoseDetailsListBean.setRelName(t.getDiagnoseDetailsList().get(i).getRelName());
                        diagnoseDetailsListBean.setPatientId(t.getDiagnoseDetailsList().get(i).getPatientId());
                        diagnoseDetailsListBean.setStatus(t.getDiagnoseDetailsList().get(i).getStatus());
                        diagnoseDetailsListBeen.add(diagnoseDetailsListBean);
                        lifecycleRecordsBean.setDiagnoseDetailsList(diagnoseDetailsListBeen);
                    }
                    map1.put(time, lifecycleRecordsBean);
                    maptime.put(time.substring(0, 7), "");
                }
                //事件
                for (int i = 0; i < t.getInspectionEventsList().size(); i++) {


                    if (time.equals(t.getInspectionEventsList().get(i).getEventTime().substring(0, 10))) {
                        LifecycleRecordsBean.InspectionEventsListBean inspectionEventsListBean = new LifecycleRecordsBean.InspectionEventsListBean();
                        inspectionEventsListBean.setEventTime(t.getInspectionEventsList().get(i).getEventTime());
                        inspectionEventsListBean.setEventDesc(t.getInspectionEventsList().get(i).getEventDesc());
                        inspectionEventsListBean.setPatientId(t.getInspectionEventsList().get(i).getPatientId());
                        inspectionEventsListBean.setDoctorId(t.getInspectionEventsList().get(i).getDoctorId());

                        //当事件为隐藏事件时直接continue
                        if(t.getInspectionEventsList().get(i).getIsHide()==0){
                            continue;
                        }
                        inspectionEventsListBeen.add(inspectionEventsListBean);
                        lifecycleRecordsBean.setInspectionEventsList(inspectionEventsListBeen);
                    }
                    map1.put(time, lifecycleRecordsBean);
                    maptime.put(time.substring(0, 7), "");
                }
                //调药记录
                for (int i = 0; i < t.getPharmacyRecordsList().size(); i++) {

                    if (time.equals(t.getPharmacyRecordsList().get(i).getEditTime().substring(0, 10))) {
                        LifecycleRecordsBean.PharmacyRecordsListBean pharmacyRecordsListBean = new LifecycleRecordsBean.PharmacyRecordsListBean();
                        pharmacyRecordsListBean.setEditTime(t.getPharmacyRecordsList().get(i).getEditTime());
                        pharmacyRecordsListBean.setEidtMessage(t.getPharmacyRecordsList().get(i).getEidtMessage());
                        pharmacyRecordsListBeen.add(pharmacyRecordsListBean);
                        lifecycleRecordsBean.setPharmacyRecordsList(pharmacyRecordsListBeen);
                    }
                    map1.put(time, lifecycleRecordsBean);
                    maptime.put(time.substring(0, 7), "");
                }
                //  患者病历
                for (int i = 0; i < t.getPatientCaseHistoryList().size(); i++) {

                    if (time.equals(t.getPatientCaseHistoryList().get(i).getMrdateTime().substring(0, 10))) {
                        LifecycleRecordsBean.PatientCaseHistoryList patientCaseHistoryList = new LifecycleRecordsBean.PatientCaseHistoryList();
                        patientCaseHistoryList.setDescription(t.getPatientCaseHistoryList().get(i).getDescription());
                        patientCaseHistoryList.setLogTime(t.getPatientCaseHistoryList().get(i).getMrdateTime());
                        patientCaseHistoryList.setTitle(t.getPatientCaseHistoryList().get(i).getTitle());
                        patientCaseHistoryLists.add(patientCaseHistoryList);
                        lifecycleRecordsBean.setPatientCaseHistoryList(patientCaseHistoryLists);
                    }
                    map1.put(time, lifecycleRecordsBean);
                    maptime.put(time.substring(0, 7), "");
                }
                //不适症状
                for (int i = 0; i < t.getTroubleDetailList().size(); i++) {
                    if (time.equals(t.getTroubleDetailList().get(i).getLogTime().substring(0, 10))) {
                        LifecycleRecordsBean.TroubleDetailListBean troubleDetailList = new LifecycleRecordsBean.TroubleDetailListBean();
                        troubleDetailList.setDescription(t.getTroubleDetailList().get(i).getDescription());
                        troubleDetailList.setLogTime(t.getTroubleDetailList().get(i).getLogTime());
                        troubleDetailList.setTroubleName(t.getTroubleDetailList().get(i).getTroubleName());
                        troubleDetailLists.add(troubleDetailList);
                        lifecycleRecordsBean.setTroubleDetailList(troubleDetailLists);
                    }
                    map1.put(time, lifecycleRecordsBean);
                    maptime.put(time.substring(0, 7), "");
                }
            }

            for (Map.Entry<String, LifecycleRecordsBean> entry : map1.entrySet()) {
                LifecycleYear.LifecycleTesmouth lifecycleTesmouth = new LifecycleYear.LifecycleTesmouth();
                lifecycleTesmouth.setMouthTime(entry.getKey());
                lifecycleTesmouth.setLifecycleTestItem(entry.getValue());
                mlifecycleTesmouths.add(lifecycleTesmouth);
                mapmouth.put(entry.getKey().substring(0, 7), "");
            }
            Map<String, List<LifecycleYear.LifecycleTesmouth>> BOSSMAP = new TreeMap<>(new Comparator<String>() {
                public int compare(String obj1, String obj2) {
                    // 降序排序
                    return obj2.compareTo(obj1);
                }
            });
            for (String time : mapmouth.keySet()) {
                List<LifecycleYear.LifecycleTesmouth> lifecycleTesmouths = new ArrayList<>();
                for (int i = 0; i < mlifecycleTesmouths.size(); i++) {
                    if (time.equals(mlifecycleTesmouths.get(i).getMouthTime().substring(0, 7))) {
                        LifecycleYear.LifecycleTesmouth lifecycleTesmouth = new LifecycleYear.LifecycleTesmouth();
                        lifecycleTesmouth.setMouthTime(mlifecycleTesmouths.get(i).getMouthTime());
                        lifecycleTesmouth.setLifecycleTestItem(mlifecycleTesmouths.get(i).getLifecycleTestItem());
                        lifecycleTesmouths.add(lifecycleTesmouth);
                    }
                }
                BOSSMAP.put(time, lifecycleTesmouths);
                mapyear.put(time.substring(0, 4), "");
            }
            Map<String, List<LifecycleYear>> year = new TreeMap<>(new Comparator<String>() {
                public int compare(String obj1, String obj2) {
                    // 降序排序
                    return obj2.compareTo(obj1);
                }
            });
            for (Map.Entry<String, List<LifecycleYear.LifecycleTesmouth>> BOSS : BOSSMAP.entrySet()) {
                LifecycleYear lifecycleTesmouth = new LifecycleYear();
                lifecycleTesmouth.setYear(BOSS.getKey());
                lifecycleTesmouth.setLifecycleTest(BOSS.getValue());
                lifecycleTestList.add(lifecycleTesmouth);
                mapyear.put(BOSS.getKey().substring(0, 4), "");
            }
            for (String time : mapyear.keySet()) {
                List<LifecycleYear> lifecycleTesmouths = new ArrayList<>();
                for (int i = 0; i < lifecycleTestList.size(); i++) {
                    if (time.equals(lifecycleTestList.get(i).getYear().substring(0, 4))) {
                        LifecycleYear lifecycleYear = new LifecycleYear();
                        lifecycleYear.setYear(lifecycleTestList.get(i).getYear());
                        lifecycleYear.setLifecycleTest(lifecycleTestList.get(i).getLifecycleTest());
                        lifecycleTesmouths.add(lifecycleYear);
                    }
                }
                year.put(time, lifecycleTesmouths);
            }
            for (Map.Entry<String, List<LifecycleYear>> BOSS : year.entrySet()) {
                ViseLog.d("sdfs");
                lifecycleHeads.add(new LifecycleHead(LifecycleTest.TITLE, BOSS.getKey()));
                for (LifecycleYear aa : BOSS.getValue()) {
                    lifecycleHeads.add(new LifecycleHead(LifecycleTest.CONTENT, aa));
                }
            }

            if (page == 1) {
                lifecycleAdapter.setNewData(lifecycleHeads);
                onLoadMore = false;
            } else {
//                lifecycleHeads.clear();
                lifecycleAdapter.getData().clear();
                lifecycleAdapter.addData(lifecycleHeads);
                if (ta.getTroubleDetailList().size() > 0 || ta.getPatientCaseHistoryList().size() > 0
                        || ta.getDiagnoseDetailsList().size() > 0 || ta.getInspectionEventsList().size() > 0 ||
                        ta.getPharmacyRecordsList().size() > 0) {
                } else {
                    onLoadMore = true;
                }
            }

        }
    }

    @Override
    public void onError(String msg) {
        if (msg != null) {
            msg(msg);
        }
    }

    @Override
    public void onRefreshUI() {
        lifecycleAdapter.notifyDataSetChanged();
    }

    //结束时间
    String endTime = format.format(new Date());

    private void goToSelectPicture(int position) {
        page=1;
        String[] Strnum = getResources().getStringArray(R.array.choose_history_life);
        imageView4.setText(Strnum[position]);
        switch (position) {
            //全部
            case 0:
                DateTime="0";
                healthRecordsPresenter.LXT_HealthRecords(0+"", endTime, page + "", LifecycleType);
                break;

            //一周
            case 1:
                DateTime = setStatetime(ConstantManger.Aweek);
                healthRecordsPresenter.LXT_HealthRecords(DateTime, endTime, page + "", LifecycleType);
                break;

            case 2:
                DateTime = setStatetime(ConstantManger.Twoweeks);
                healthRecordsPresenter.LXT_HealthRecords(DateTime, endTime, page + "", LifecycleType);
                break;

            case 3:
                DateTime = setStatetime(ConstantManger.January);
                healthRecordsPresenter.LXT_HealthRecords(DateTime, endTime, page + "", LifecycleType);
                break;

            case 4:
                DateTime = setStatetime(ConstantManger.March);
                healthRecordsPresenter.LXT_HealthRecords(DateTime, endTime, page + "", LifecycleType);
                break;

            case 5:
                DateTime = setStatetime(ConstantManger.Halfayear);
                healthRecordsPresenter.LXT_HealthRecords(DateTime, endTime, page + "", LifecycleType);
                break;

            case ACTION_TYPE_LAST:
                dialog_my_date_code dialog = new dialog_my_date_code(this);
                dialog.setListener(this);
                dialog.show();
                break;

        }
    }

    /**
     * 根据传入的参数计算出前多少天的数据
     *
     * @param DataTime
     * @return
     */
    public String setStatetime(int DataTime) {
        Calendar c = Calendar.getInstance();
        c.add(Calendar.DATE, DataTime);
        Date monday = c.getTime();
        String preMonday = format.format(monday);
        return preMonday;
    }

    //自定义时间查询
    @Override
    public void DialogDetermine(String statsTime, String endTime) {
        healthRecordsPresenter.LXT_HealthRecords(statsTime, endTime, page + "", LifecycleType);
    }

    @Override
    public void onRefresh() {
        page = 1;
        healthRecordsPresenter.LXT_HealthRecords(DateTime, endTime, page + "", LifecycleType);
        lifecycleAdapter.setEnableLoadMore(false);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                //下拉后添加新数据
                swipeLayout.setRefreshing(false);//下拉刷新关闭
                lifecycleAdapter.setEnableLoadMore(true);
            }
        }, delayMillis);
    }

    @Override
    public void onLoadMoreRequested() {
        page++;//下拉时page递增
        healthRecordsPresenter.LXT_HealthRecords(DateTime, endTime, page + "", LifecycleType);
        mRecyclerView.postDelayed(new Runnable() {
            @Override
            public void run() {
                //判断当返回的数据为空时停止下拉刷新
                if (onLoadMore) {
                    lifecycleAdapter.loadMoreEnd();
                } else {
                    lifecycleAdapter.loadMoreComplete();
                    lifecycleAdapter.notifyDataSetChanged();
                }
            }

        }, delayMillis);
    }
}
